package com.sunday.pinxinghui.model.index;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.support.annotation.MainThread;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.CharacterParser;
import com.sunday.common.utils.LetterUtil;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.SlideView;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.MainActivity;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CityListAdapter;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Province;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.service.LocationService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/29.
 */

public class SelectCityListActivity extends BaseActivity implements SlideView.OnTouchListener {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.index)
    SlideView slideView;
    @Bind(R.id.current_city)
    TextView currentCity;

    private List<Province> cityList = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;
    private CityListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_city);
        ButterKnife.bind(this);
        titleView.setText("选择城市");
        recyclerView.setPadding(0, 0, 0, 0);
        linearLayoutManager = new LinearLayoutManager(mContext);
        adapter = new CityListAdapter(mContext, cityList);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider).build());
        recyclerView.setAdapter(adapter);
        slideView.setOnTouchListener(this);
        currentCity.setText("当前城市：" + BaseApplication.getInstance().getCityName());
        getAllCity();
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getAllCity();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.text_view:
                        Province city = (Province) v.getTag();
                        Intent data = new Intent();
                        BaseApplication.getInstance().setCityId(city.getId());
                        BaseApplication.getInstance().setCityName(city.getName());
                        currentCity.setText("当前城市：" + city.getName());
                        data.putExtra("cityId", Integer.valueOf(city.getId()));
                        data.putExtra("cityName", city.getName());
                        setResult(RESULT_OK, data);
                        //BaseApplication.getInstance().setCityName(city.getValue());
                        //BaseApplication.getInstance().setCityId(Integer.valueOf(city.getId()));
                        // EventBus.getDefault().post(city);
                        finish();
                        break;

                }
            }
        });

    }

    @Override
    public void back(View v) {
        Intent data = new Intent();
        data.putExtra("cityName", BaseApplication.getInstance().getCityName());
        //setCityId
        setResult(RESULT_OK, data);
        finish();
    }

    @OnClick(R.id.btn_loc)
    void reLoc() {
        requestLocation();
    }

    public LocationService locationService;
    private LocationClient mClient;

    public void requestLocation() {
        locationService = BaseApplication.getInstance().getLocationService();
        LocationClientOption mOption = locationService.getDefaultLocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mClient = new LocationClient(getApplicationContext());
        mClient.setLocOption(mOption);
        mClient.registerLocationListener(locListener);
        mClient.start();
    }

    /***
     * 定位结果回调，在此方法中处理定位结果
     */
    BDLocationListener locListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub

            if (location != null && location.getLocType() != BDLocation.TypeServerError) {
                Log.i(TAG, "定位成功");
                Log.i(TAG, "currentThread" + Thread.currentThread());
                mClient.stop();
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                SharePerferenceUtils.getIns(getApplicationContext()).putString("latitude", latitude);
                SharePerferenceUtils.getIns(getApplicationContext()).putString("longitude", longitude);
                BaseApplication.getInstance().setCityName(location.getCity());
                BaseApplication.getInstance().setLati(latitude);
                BaseApplication.getInstance().setLongti(longitude);
                ((SelectCityListActivity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //此时已在主线程中，可以更新UI了
                        currentCity.setText("当前城市：" + BaseApplication.getInstance().getCityName());
                    }
                });
            } else {
                ToastUtils.showToast(getApplicationContext(), "定位失败，请开启位置服务后重新定位");
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };


    private void getAllCity() {
        Call<ResultDO<List<Province>>> call = ApiClient.getApiAdapter().getAllCity();
        call.enqueue(new Callback<ResultDO<List<Province>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Province>>> call, Response<ResultDO<List<Province>>> response) {
                ptrFrame.refreshComplete();
                ResultDO<List<Province>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0 && resultDO.getResult() != null) {
                    cityList.clear();
                    cityList.addAll(resultDO.getResult());
                    try {
                        for (Province item : cityList) {
                            item.setIndex(LetterUtil.getFirstAllLetter(item.getName()).toUpperCase());
                        }
                    } catch (Exception e) {
                        return;
                    }
                    Collections.sort(cityList, new Compara());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Province>>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });


    }

    @Override
    public void onTouch(String letter) {
        for (int i = 0; i < cityList.size(); i++) {
            if (letter.equals(cityList.get(i).getIndex())) {
                smoothMoveToPosition(i);
                break;
            }
        }

    }


    private void smoothMoveToPosition(int index) {
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        if (index <= firstItem) {
            recyclerView.smoothScrollToPosition(index);
        } else if (index <= lastItem) {
            int top = recyclerView.getChildAt(index - firstItem).getTop();
            recyclerView.smoothScrollBy(0, top);
        } else {
            recyclerView.smoothScrollToPosition(index);
        }

    }

    private class Compara implements Comparator<Province> {

        @Override
        public int compare(Province lhs, Province rhs) {
            return lhs.getIndex().compareTo(rhs.getIndex());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        slideView.onDestroy();
    }

}

